package cn.edu.ujn.bmis.action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import cn.edu.ujn.bmis.model.Book;
import cn.edu.ujn.bmis.model.Donator;
import cn.edu.ujn.bmis.model.SysPara;
import cn.edu.ujn.bmis.model.UserInfo;
import cn.edu.ujn.bmis.service.BookManager;
import cn.edu.ujn.bmis.service.DonatorManager;
import cn.edu.ujn.bmis.service.SysParaManager;
import cn.edu.ujn.bmis.service.UserInfoManager;
import cn.edu.ujn.bmis.tools.Helper;

import com.jspsmart.upload.SmartUpload;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

@Component("Book")
@Scope("prototype")
public class BookAction extends ActionSupport {

	private static final long serialVersionUID = -5888526456292043959L;
	private Book book;
	private String targetType = "navTab"; // navTab或dialog，用来标记是navTab上的分页还是dialog上的分页
	private BookManager bookManager;
	private List<Book> bookList = new ArrayList<Book>();
	private Helper helper;
	private int pageNum = 1;
	private int currentPage = 1; // 当前是第几页
	private int totalCount = 0; // 总条数
	private int numPerPage = 5; // 每页显示多少条
	private int pageNumShown = 5; // 页标数字多少个
	private int pageCount = 0; // 总页数
	private String orderField;
	private String orderDirection;
	private String ids;
	private String bookName;
	private String donatorName;
	private String author;
	private String press;
	private long bookId;
	private String donatorTimeStart;
	private String donatorTimeEnd;
	private String isbn;
	private String functionNum;
	private String operatorId;
	private String operatorName;
	private SysParaManager sysParaManager;
	private List<SysPara> sysParaList = new ArrayList<SysPara>();
	private UserInfoManager userInfoManager;
	private DonatorManager donatorManager;
	private String bookType;
	// myFile属性用来封装上传的文件  
    private File myFile;  
      
    // myFileContentType属性用来封装上传文件的类型  
    private String myFileContentType;  
  
    // myFileFileName属性用来封装上传文件的文件名  
    private String myFileFileName;  
	
    public void uploadBook(){
    	try {
			 //基于myFile创建一个文件输入流  
	        InputStream is = new FileInputStream(myFile);  
	          
	        // 设置上传文件目录  
	        String uploadPath = ServletActionContext.getServletContext()  
	                .getRealPath("/upload");  
	          
	        // 设置目标文件  
	        File toFile = new File(uploadPath, this.getMyFileFileName());  
	          
	        // 创建一个输出流  
	        OutputStream os = new FileOutputStream(toFile);  
	  
	        //设置缓存  
	        byte[] buffer = new byte[1024];  
	  
	        int length = 0;  
	  
	        //读取myFile文件输出到toFile文件中  
	        while ((length = is.read(buffer)) > 0) {  
	            os.write(buffer, 0, length);  
	        }  
	        //关闭输入流  
	        is.close();  
	          
	        //关闭输出流  
	        os.close(); 
	        Helper.out("300", "图片上传成功", "", "", "", "");
		} catch (Exception e) {
			e.printStackTrace();
			Helper.out("300", "图片上传失败", "", "", "", "");
		}
    }
	/**
	 * 新增图书
	 */
	public void addBook() {
		// 检查输入的捐赠人编号是否存在
		String hql_check = "";
		List<Donator> donatorList = new ArrayList<Donator>();
		hql_check = "from Donator d where d.donatorId='" + book.getDonator().getDonatorId() + "'";
		donatorList = donatorManager.findDonator(hql_check);
		if (donatorList.size() <= 0) {
			Helper.out("300", "输入的捐赠人编号不存在请检查！", "", "", "", "");
			return;
		}
		if (bookManager.addBook(book)) {
			Helper.out("200", "图书添加成功", "closeCurrent", "", "", "manageBook");
		} else {
			Helper.out("300", "图书添加失败", "", "", "", "");
		}
	}
	
	/**
	 * 进入图书管理页面
	 */
	public String beforeAdFindBook(){
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql="";
		hql="select s.value from SysPara s where s.name='图书种类'";
		sysParaList=sysParaManager.findSysPara(hql);
		return SUCCESS;
	}
	/**
	 * 进入读者图书检索页面
	 */
	public String beforeFindBook(){
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql="";
		hql="select s.value from SysPara s where s.name='图书种类'";
		sysParaList=sysParaManager.findSysPara(hql);
		return SUCCESS;
	}
	/**
	 * 查看图书基本信息
	 */
	@SuppressWarnings("unchecked")
	public String findBook() {
		String hql = "";
		String hql_size = "";
		String hql_type="";
		//功能权限验证 hxlbookad0001
		if(!helper.checkFunction(functionNum)){ 
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		if (bookName == null) {
			bookName = "";
		}
		if (donatorName == null) {
			donatorName = "";
		}
		if (press == null) {
			press = "";
		}
		if (author == null) {
			author = "";
		}
		if(bookType ==null){
			bookType="";
		}
		hql_type="select s.value from SysPara s where s.name='图书种类'";
		sysParaList=sysParaManager.findSysPara(hql_type);
		this.currentPage = this.pageNum;
		if (!"".equals(donatorName.trim())) {
			hql = "select b from Book b,Donator d where b.donator.donatorId=d.donatorId and b.bookName like '%"
					+ bookName.trim()
					+ "%' and b.author like '%"
					+ author.trim()
					+ "%' and b.press like '%"
					+ press.trim()
					+ "%' and b.donator.donatorName like '%"
					+ donatorName.trim() + "%' and b.bookType like '%"+bookType.trim()+"%'";
			hql_size = "select count(*) from Book b,Donator d where b.donator.donatorId=d.donatorId and b.bookName like '%"
					+ bookName.trim()
					+ "%' and b.author like '%"
					+ author.trim()
					+ "%' and b.press like '%"
					+ press.trim()
					+ "%' and d.donatorName like '%"
					+ donatorName.trim()
					+ "%'  and b.bookType like '%"+bookType.trim()+"%'";
		} else {
			hql = "select b from Book b,Donator d where b.donator.donatorId=d.donatorId and b.bookName like '%"
					+ bookName.trim()
					+ "%' and b.author like '%"
					+ author.trim()
					+ "%' and b.press like '%"
					+ press.trim()
					+ "%' and b.bookType like '%"+bookType.trim()+"%'";
			hql_size = "select count(*) from Book b,Donator d where b.donator.donatorId=d.donatorId and b.bookName like '%"
					+ bookName.trim()
					+ "%' and b.author like '%"
					+ author.trim()
					+ "%' and b.press like '%"
					+ press.trim()
					+ "%' and b.bookType like '%"+bookType.trim()+"%'";
		}
		totalCount = helper.findSize(hql_size);
		pageCount = totalCount % numPerPage == 0 ? totalCount / numPerPage
				: totalCount / numPerPage + 1;
		bookList = helper.fenYe(hql, this.currentPage, this.numPerPage);
		return SUCCESS;
	}
	
	/**
	 * 进入捐书统计查询页面
	 */
	public String beforeFindDonatorBook(){
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql_type="";
		hql_type="select s.value from SysPara s where s.name='图书种类'";
		sysParaList=sysParaManager.findSysPara(hql_type);
		return SUCCESS;
	}

	/**
	 * 查看图书捐赠情况
	 */
	@SuppressWarnings("unchecked")
	public String findDonatorBook() {
		String hql = "";
		String hql_size = "";
		String hql_type="";
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		this.currentPage = this.pageNum;
		hql_type="select s.value from SysPara s where s.name='图书种类'";
		sysParaList=sysParaManager.findSysPara(hql_type);
		hql = "select b from Book b,Donator d where b.donator.donatorId=d.donatorId";
		hql_size = " select count(*) from Book b,Donator d where b.donator.donatorId=d.donatorId";
		if (!(donatorTimeStart == null || "".equals(donatorTimeStart))
				&& !(donatorTimeEnd == null || "".equals(donatorTimeEnd))) {
			hql += " and  b.donatorTime>='" + donatorTimeStart.trim()
					+ "' and b.donatorTime<='" + donatorTimeEnd.trim() + "'";
			hql_size += " and  b.donatorTime>='" + donatorTimeStart.trim()
					+ "' and b.donatorTime<='" + donatorTimeEnd.trim() + "'";
			if (!(donatorName == null || "".equals(donatorName))) {
				hql += "and b.donator.donatorName='" + donatorName.trim() + "'";
				hql_size += "and b.donator.donatorName='" + donatorName.trim()
						+ "'";
			}
			if (!(isbn == null || "".equals(isbn))) {
				hql += " and b.isbn='" + isbn.trim() + "'";
				hql_size += " and b.isbn='" + isbn.trim() + "'";
			}
			if(bookType!=null&&!"".equals(bookType)){
				hql += " and b.bookType='" + bookType.trim() + "'";
				hql_size += " and b.bookType='" + bookType.trim() + "'";
			}
		} else if ((donatorTimeStart == null || "".equals(donatorTimeStart))
				&& (donatorTimeEnd == null || "".equals(donatorTimeEnd))) {
			if (!(donatorName == null || "".equals(donatorName))) {
				hql += " and b.donator.donatorName='" + donatorName.trim() + "'";
				hql_size += " and b.donator.donatorName='" + donatorName.trim()
						+ "'";
			}
			if (!(isbn == null || "".equals(isbn))) {
				hql += " and b.isbn='" + isbn.trim() + "'";
				hql_size += " and b.isbn='" + isbn.trim() + "'";
			}
			if(bookType!=null&&!"".equals(bookType)){
				hql += " and b.bookType='" + bookType.trim() + "'";
				hql_size += " and b.bookType='" + bookType.trim() + "'";
			}
		}
		totalCount = helper.findSize(hql_size);
		pageCount = totalCount % numPerPage == 0 ? totalCount / numPerPage
				: totalCount / numPerPage + 1;
		bookList = helper.fenYe(hql, this.currentPage, this.numPerPage);
		return SUCCESS;
	}

	/**
	 * 删除图书信息
	 */
	public void deleteBook() {
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
			return;
		}
		String hql = "";
		hql = "delete from Book b where bookId in (" + ids + ")";
		if (bookManager.update(hql)) {
			Helper.out("200", "图书删除成功", "", "", "", "manageBook");
		} else {
			Helper.out("300", "图书删除失败", "", "", "", "");
		}
	}
	
	@SuppressWarnings("unchecked")
	public String beforeAddBook(){
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql="";
		hql="select s.value from SysPara s where s.name='图书种类'";
		sysParaList=sysParaManager.findSysPara(hql);
		//操作员信息
		Map session = (Map) ActionContext.getContext().getSession();
		UserInfo users = new UserInfo();
		users = (UserInfo) session.get("user");
		operatorId = users.getUserId();
		operatorName = users.getUserName();
		return SUCCESS;
	}

	/**
	 * 修改前的查找
	 */
	public String beforeupdateBook() {
		//功能权限验证
		if(!helper.checkFunction(functionNum)){
			Helper.out("403", "该用户没有此功能权限!", "", "", "", "");
		}
		String hql_type="";
		hql_type="select s.value from SysPara s where s.name='图书种类'";
		sysParaList=sysParaManager.findSysPara(hql_type);
		String hql = "from Book b where b.bookId='" + bookId + "'";
		bookList = bookManager.findBook(hql);
		if (bookList.size() > 0) {
			book = bookList.get(0);
		}
		return SUCCESS;
	}

	/**
	 * 修改图书信息
	 */
	public void updateBook() {
		// 检查输入的捐赠人编号是否存在
		String hql_check = "";
		List<UserInfo> userInfoList = new ArrayList<UserInfo>();
		hql_check = "from UserInfo u where u.userId='" + book.getDonator().getDonatorId() + "'";
		userInfoList = userInfoManager.findUserInfo(hql_check);
		if (userInfoList.size() <= 0) {
			Helper.out("300", "输入的捐赠人编号不存在请检查！", "", "", "", "");
			return;
		}
		if (bookManager.update(book)) {
			Helper.out("200", "图书修改成功", "closeCurrent", "", "", "manageBook");
		} else {
			Helper.out("300", "图书修改失败", "", "", "", "");
		}
	}

	public Book getBook() {
		return book;
	}

	public void setBook(Book book) {
		this.book = book;
	}

	public BookManager getBookManager() {
		return bookManager;
	}

	@Resource(name = "bookManager")
	public void setBookManager(BookManager bookManager) {
		this.bookManager = bookManager;
	}

	@SuppressWarnings("unchecked")
	public List getBookList() {
		return bookList;
	}

	@SuppressWarnings("unchecked")
	public void setBookList(List bookList) {
		this.bookList = bookList;
	}

	public Helper getHelper() {
		return helper;
	}

	@Resource(name = "helper")
	public void setHelper(Helper helper) {
		this.helper = helper;
	}

	public String getTargetType() {
		return targetType;
	}

	public void setTargetType(String targetType) {
		this.targetType = targetType;
	}

	public int getPageNum() {
		return pageNum;
	}

	public void setPageNum(int pageNum) {
		this.pageNum = pageNum;
	}

	public int getCurrentPage() {
		return currentPage;
	}

	public void setCurrentPage(int currentPage) {
		this.currentPage = currentPage;
	}

	public int getTotalCount() {
		return totalCount;
	}

	public void setTotalCount(int totalCount) {
		this.totalCount = totalCount;
	}

	public int getNumPerPage() {
		return numPerPage;
	}

	public void setNumPerPage(int numPerPage) {
		this.numPerPage = numPerPage;
	}

	public int getPageNumShown() {
		return pageNumShown;
	}

	public void setPageNumShown(int pageNumShown) {
		this.pageNumShown = pageNumShown;
	}

	public int getPageCount() {
		return pageCount;
	}

	public void setPageCount(int pageCount) {
		this.pageCount = pageCount;
	}

	public String getOrderField() {
		return orderField;
	}

	public void setOrderField(String orderField) {
		this.orderField = orderField;
	}

	public String getOrderDirection() {
		return orderDirection;
	}

	public void setOrderDirection(String orderDirection) {
		this.orderDirection = orderDirection;
	}

	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getBookName() {
		return bookName;
	}

	public void setBookName(String bookName) {
		this.bookName = bookName;
	}

	public String getDonatorName() {
		return donatorName;
	}

	public void setDonatorName(String donatorName) {
		this.donatorName = donatorName;
	}

	public String getAuthor() {
		return author;
	}

	public void setAuthor(String author) {
		this.author = author;
	}

	public String getPress() {
		return press;
	}

	public void setPress(String press) {
		this.press = press;
	}

	public long getBookId() {
		return bookId;
	}

	public void setBookId(long bookId) {
		this.bookId = bookId;
	}

	public String getDonatorTimeStart() {
		return donatorTimeStart;
	}

	public void setDonatorTimeStart(String donatorTimeStart) {
		this.donatorTimeStart = donatorTimeStart;
	}

	public String getDonatorTimeEnd() {
		return donatorTimeEnd;
	}

	public void setDonatorTimeEnd(String donatorTimeEnd) {
		this.donatorTimeEnd = donatorTimeEnd;
	}

	public String getIsbn() {
		return isbn;
	}

	public void setIsbn(String isbn) {
		this.isbn = isbn;
	}

	public String getFunctionNum() {
		return functionNum;
	}

	public void setFunctionNum(String functionNum) {
		this.functionNum = functionNum;
	}

	public String getOperatorId() {
		return operatorId;
	}

	public void setOperatorId(String operatorId) {
		this.operatorId = operatorId;
	}

	public String getOperatorName() {
		return operatorName;
	}

	public void setOperatorName(String operatorName) {
		this.operatorName = operatorName;
	}

	public SysParaManager getSysParaManager() {
		return sysParaManager;
	}
	
	@Resource(name="sysParaManager")
	public void setSysParaManager(SysParaManager sysParaManager) {
		this.sysParaManager = sysParaManager;
	}

	public List<SysPara> getSysParaList() {
		return sysParaList;
	}

	public UserInfoManager getUserInfoManager() {
		return userInfoManager;
	}

	@Resource(name="userInfoManager")
	public void setUserInfoManager(UserInfoManager userInfoManager) {
		this.userInfoManager = userInfoManager;
	}

	public String getBookType() {
		return bookType;
	}

	public void setBookType(String bookType) {
		this.bookType = bookType;
	}

	public File getMyFile() {
		return myFile;
	}

	public void setMyFile(File myFile) {
		this.myFile = myFile;
	}

	public String getMyFileContentType() {
		return myFileContentType;
	}

	public void setMyFileContentType(String myFileContentType) {
		this.myFileContentType = myFileContentType;
	}

	public String getMyFileFileName() {
		return myFileFileName;
	}

	public void setMyFileFileName(String myFileFileName) {
		this.myFileFileName = myFileFileName;
	}
	public DonatorManager getDonatorManager() {
		return donatorManager;
	}
	
	@Resource(name="donatorManager")
	public void setDonatorManager(DonatorManager donatorManager) {
		this.donatorManager = donatorManager;
	}
	
	
}
